﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace MTO.Framework.Common.DataAnnotations
{
    /// <summary>
    /// Est utilisée pour enregistrer le lien qui existe entre les classes utilisant l'attribut MetadataTypeAttribute et les
    /// classes qui implémentent le Metadata.
    /// </summary>
    public static class MetadataTypesRegister
    {
        private static bool installed = false;
        private static object installedLock = new object();

        public static void RegisterMetadataTypes(Assembly assembly)
        {
            if (installed)
            {
                return;
            }

            lock (installedLock)
            {
                if (installed)
                {
                    return;
                }

                foreach (Type type in assembly.GetTypes())
                {
                    foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true))
                    {
                        TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type);
                    }
                }

                installed = true;
            }
        }
    }
}
